<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>代理商趋势环比和同比</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
<link rel="stylesheet" href="{{asset('/layuiadmin/layui/css/layui.css')}}" media="all">
<link rel="stylesheet" href="{{asset('/layuiadmin/style/admin.css')}}" media="all">
<style>
    .edit{background-color: #ed9c3a;}
    .shenhe{background-color: #429488;}
    .see{background-color: #7cb717;}
    .tongbu{background-color: #4c9ef8;color:#fff;border-radius:3.5px}
    .cur{color:#21c4f5;}
    .userbox,.storebox{height:190px;margin-right:0; overflow-y: auto; z-index: 999; position: absolute; left: 0px; top: 63px; width:298px; background-color:#ffffff; border: 1px solid #ddd;}
    .userbox .list,.storebox .list{height:38px;line-height: 38px;cursor:pointer; padding-left:10px;}
    .userbox .list:hover,.storebox .list:hover{background-color:#eeeeee;}
    .yname{font-size: 13px; color: #444; margin-bottom:8px;}
</style>
</head>
<body>

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12" style="margin-top:0px">
            <div class="layui-fluid">
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md12">
                        <div class="layui-card">
                            <div class="layui-card-header">代理商趋势环比和同比列表</div>
                            <div class="layui-card-body">
                                <div class="layui-btn-container" style="font-size:14px;min-height:600px">
                                    <div style="font-size:14px">
                                        <div class="layui-form" lay-filter="component-form-group" style="margin-right:0;display: flex;">
                                            <div class="layui-form-item agentSelect">
                                                <div class="layui-input-block" style="margin-left:10px;border-radius:5px">
                                                    <text class="yname">代理商名称</text>
                                                    <input type="text" style="border-radius:5px"tyle="border-radius:5px" name="schoolname" lay-verify="schoolname" autocomplete="off" placeholder="请输入代理商名称" class="layui-input transfer">
                                                    <div class="userbox" style='display: none'></div>
                                                </div>
                                            </div>
                                            <div class="layui-form-item storeSelect">
                                                <div class="layui-input-block" style="margin-left:10px;border-radius:5px">
                                                    <text class="yname">门店名称</text>
                                                    <input type="text" style="border-radius:5px"name="schoolname" lay-verify="schoolname" autocomplete="off" placeholder="请输入门店名称" class="layui-input inputstore">
                                                    <div class="storebox" style='display: none'></div>
                                                </div>
                                            </div>
                                            <div class="layui-form-item">
                                                <div class="layui-input-block" style="margin-left:10px;border-radius:5px">
                                                    <text class="yname">时间选择</text>
                                                    <input type="text" style="border-radius:5px;width:250px" id="start-item-range" class="layui-input test-item" placeholder="时间选择">
                                                </div>
                                            </div>
                                            <!-- <div class="layui-form-item">
                                                <div class="layui-input-block" style="margin-left:10px;border-radius:5px">
                                                    <text class="yname">结束时间</text>
                                                    <input type="text" style="border-radius:5px" id="end-item" class="layui-input end-item test-item" placeholder="结束时间">
                                                </div>
                                            </div> -->
                                            <div class="layui-form-item">
                                                    <div class="layui-input-block" style="margin-left:10px;border-radius:5px">
                                                        <text class="yname">对比的时间选择</text>
                                                        <input type="text" style="border-radius:5px;width:250px" id="start-item1-range" class="layui-input test-item" placeholder="对比的时间选择">
                                                    </div>
                                                </div>
                                                <!-- <div class="layui-form-item">
                                                    <div class="layui-input-block" style="margin-left:10px;border-radius:5px">
                                                        <text class="yname">对比的结束时间</text>
                                                        <input type="text" style="border-radius:5px" id="end-item1" class="layui-input end-item1 test-item1" placeholder="对比的结束时间">
                                                    </div>
                                                </div> -->
                                            <div class="layui-form-item">
                                                <div class="layui-input-block" style="margin-left:10px;border-radius:5px;width:175px;">
                                                    <text class="yname">增长比例最小值</text>
                                                    <input type="text" style="border-radius:5px" name="schoolname" lay-verify="schoolname" autocomplete="off" placeholder="请输入增长比例最小值" class="layui-input trend_rate_min">
                                                </div>
                                            </div>
                                            <div class="layui-form-item">
                                                <div class="layui-input-block" style="margin-left:10px;border-radius:5px;width:175px;">
                                                    <text class="yname">增长比例最大值</text>
                                                    <input type="text" style="border-radius:5px" name="schoolname" lay-verify="schoolname" autocomplete="off" placeholder="请输入增长比例最大值" class="layui-input trend_rate_max">
                                                </div>
                                            </div>
                                            <div class="layui-form-item">
                                                <div class="layui-inline">
                                                    <button class="layui-btn layuiadmin-btn-list" lay-submit="" lay-filter="LAY-app-contlist-search" style="margin-left:20px;border-radius:5px;margin-top:25px;margin-bottom: 0;height:36px;line-height: 36px;">
                                                        <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                                                    </button>
                                                </div>
                                                <button class="layui-btn export" style="border-radius:5px;margin-top:25px;margin-bottom: 4px;height:36px;line-height: 36px;">导出</button>
                                            </div>
                                        </div>
                                    </div>
                                    <div>
                                        <table class="layui-hide" id="test-table-page1" lay-filter="test-table-page1"></table>
                                    </div>
                                </div>

                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<input type="hidden" class="store_id">
<input type="hidden" class="user_id">
<input type="hidden" class="start-item">
<input type="hidden" class="end-item">
<input type="hidden" class="start-item1">
<input type="hidden" class="end-item1">

<script src="{{asset('/layuiadmin/layui/layui.js')}}"></script>
<script>
var token = localStorage.getItem("Usertoken");
var str=location.search;

layui.config({
    base: '../../layuiadmin/' //静态资源所在路径
}).extend({
    index: 'lib/index' //主入口模块
}).use(['index','form','table','laydate', 'element'], function(){
    var $ = layui.$
        ,admin = layui.admin
        ,form = layui.form
        ,table = layui.table
        ,laydate = layui.laydate
        ,element = layui.element;

    // 未登录,跳转登录页面
    $(document).ready(function(){
        if(token==null){
        window.location.href="{{url('/user/login')}}";
        }
    });

    var s_storename=localStorage.getItem('s_storename');

    // 获取当前日期
    var now = new Date();
    var nowDayOfWeek = now.getDay(); // 今天本周的第几天
    var nowDay = now.getDate(); // 当前日
    var nowMonth = now.getMonth(); // 当前月
    var nowYear = now.getFullYear(); // 当前年

    // 获得本周的开始日期
    var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1);
    // 获得本周的结束日期
    var weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek) + 1);

    // 获得上周的开始日期
    var lastWeekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 6);
    // 获得上周的结束日期
    var lastWeekEndDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);

    // 格式化日期
    function formatDate(date) {
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        return year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day);
    }
    let weekStartTime = formatDate(weekStartDate);
    let weekEndTime = formatDate(weekEndDate);
    let lastWeekStartTime = formatDate(lastWeekStartDate);
    let lastWeekEndTime = formatDate(lastWeekEndDate);
    $('.start-item').val(weekStartTime)
    $('.end-item').val(weekEndTime)
    $('.start-item1').val(lastWeekStartTime)
    $('.end-item1').val(lastWeekEndTime)
    var starttime = laydate.render({
        elem: '#start-item-range'
        ,type: 'date'
        ,range:'至'
        ,value: weekStartTime + ' 至 ' + weekEndTime
        ,done: function(value, date, endDate){
            if(value){
                $('.start-item').val(value.substring(0,10))
                $('.end-item').val(value.substring(13,value.length))
            }else{
                $('.start-item').val('')
                $('.end-item').val('')
            }
        }
    });

    laydate.render({
        elem: '#start-item1-range'
        ,type: 'date'
        ,range:'至'
        ,value: lastWeekStartTime + ' 至 ' + lastWeekEndTime
        ,done: function(value, date, endDate){
            if(value){
                $('.start-item1').val(value.substring(0,10))
                $('.end-item1').val(value.substring(13,value.length))
            }else{
                $('.start-item1').val('')
                $('.end-item1').val('')
            }
        }
    });

    //增长比例最大值默认为“-20”
    $('.trend_rate_max').val(-20)
   
    // 选择门店
    $.ajax({
        url : "{{url('/api/user/store_lists')}}",
        data : {token:token,l:100},
        type : 'post',
        success : function(data) {
            //console.log(data);
            var optionStr = "";
            for(var i=0;i<data.data.length;i++){
                optionStr += "<option value='" + data.data[i].store_id + "' "+">" + data.data[i].store_name + "</option>";
            }
            $("#schooltype").append('<option value="">选择门店</option>'+optionStr);
            // layui.form.render('select');
        },
        error : function(data) {
            alert('查找板块报错');
        }
    });

    $(".transfer").bind("input propertychange", function(event){
        //         console.log($(this).val());
        user_name = $(this).val();
        if (user_name.length == 0) {
            $('.userbox').html('');
            $('.userbox').hide();
            $('.user_id').val('')
        } else {
            $.post("{{url('/api/user/get_sub_users')}}",
            {
                token:token
                ,user_name:$(this).val()
                ,self:'1'
            },function(res){
                var html="";

                if(res.t==0){
                    $('.userbox').html('');
                }else{
                    for(var i=0;i<res.data.length;i++){
                        html+='<div class="list" data='+res.data[i].id+'>'+res.data[i].name+'-'+res.data[i].level_name+'</div>'
                    }
                    $(".userbox").show();
                    $('.userbox').html('');
                    $('.userbox').append(html);
                }
            },"json");
        }
    });

    $(".userbox").on("click",".list",function(){
        $('.transfer').val($(this).html());
        $('.user_id').val($(this).attr('data'));
        $('.userbox').hide();
    });

    $(".inputstore").bind("input propertychange",function(event){
        store_name = $(this).val();
        if (store_name.length == 0) {
            $('.storebox').html('');
            $('.storebox').hide();
            $('.store_id').val('')
        } else {
            $.post("{{url('/api/user/store_lists')}}",
            {
                token:token
                ,store_name:$(this).val()
                ,l:100
            },function(res){
                var html="";
                if(res.t==0){
                    $('.storebox').html('');
                }else{
                    for(var i=0;i<res.data.length;i++){
                        html+='<div class="list" data='+res.data[i].store_id+'>'+res.data[i].store_name+'</div>'
                    }
                    $(".storebox").show();
                    $('.storebox').html('');
                    $('.storebox').append(html);
                }
            },"json");
        }
    });

    $(".storebox").on("click",".list",function(){
        $('.inputstore').val($(this).html());
        $('.store_id').val($(this).attr('data'));
        $('.storebox').hide();
    });

    // 渲染表格
    let starttimels = $('.start-item').val();
    let endtimels = $('.end-item').val();
    let startitemls1 = $('.start-item1').val();
    let endtimels1 = $('.end-item1').val()
    let startDateBefore = ''
    let endDateBefore = '';
    let startDate = '';
    let endDate = '';
    if(starttimels && endtimels){
        //处理开始时间和结束时间
        startDate = starttimels.length<12 ? starttimels + ' 00:00:00' : starttimels;
        endDate = endtimels.length<12 ? endtimels + ' 23:59:59' : endtimels;
    }else{
        layer.msg('请选择时间!') 
        return
    }
    if(startitemls1 && endtimels1){
        //处理对比的开始时间和结束时间
        startDateBefore = startitemls1.length<12 ? startitemls1 + ' 00:00:00' : startitemls1;
        endDateBefore = endtimels1.length<12 ? endtimels1 + ' 23:59:59' : endtimels1;
    }else{
        layer.msg('请选择对比时间!') 
        return
    }
    var pageLoading1 = layer.msg('数据请求中..', {
        icon: 16
        ,shade: 0.3
        ,time: false
    });
    var tableId = table.render({
        elem: '#test-table-page1'
        ,url: "{{url('/api/v2/Bill/User/TrendChart/agentTrend')}}"
        ,method: 'get'
        ,where:{
            store_pid:$('.store_id').val(),
            agent_id:$('.user_id').val(),
            startDate:startDate,
            endDate:endDate,
            startDateBefore:startDateBefore,
            endDateBefore:endDateBefore,
            trend_rate_min:$('.trend_rate_min').val(),
            trend_rate_max:$('.trend_rate_max').val(),
            token:token
        }
        ,request:{
            pageName: 'page'
            ,limitName: 'pagesize'
        }
        ,page: true
        ,cellMinWidth: 100
        ,cols: [[
            {field:'agent_id_val',align:'center',title: '代理商ID'}
            ,{field:'agent_name',align:'center',title: '代理商名称'}
            ,{field:'after_receipt_amount',align:'center',title: '当前时间段增长金额'}
            ,{field:'before_receipt_amount',align:'center',title: '上个时间段增长金额'}
            ,{field:'trend_amount',align:'center',title: '净增长金额'}
            ,{field:'trend_rate',align:'center',title: '增长比例'}
        ]]
        ,response: {
            statusName: 'status' //数据状态的字段名称，默认：code
            ,statusCode: 1 //成功的状态码，默认：0
            ,msgName: 'message' //状态信息的字段名称，默认：msg
            ,countName: 'total' //数据总数的字段名称，默认：count
            ,dataName: 'data' //数据列表的字段名称，默认：data
        }
        ,done: function(res, curr, count){
            $('th').css({'font-weight': 'bold', 'font-size': '15','color': 'black','background':'linear-gradient(#f2f2f2,#cfcfcf)'});	//进行表头样式设置
            if(pageLoading1){
                layer.close(pageLoading1);
            }
        }
    });

    table.on('tool(test-table-page)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        var e = obj.data; //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var tr = obj.tr; //获得当前行 tr 的DOM对象
        //          console.log(e);
        // localStorage.setItem('s_store_id', e.store_id);
    });

    // 选择门店
    form.on('select(schooltype)', function(data){
        var store_id = data.value;
        $('.store_id').val(store_id);
    });

    // 选择业务员
    form.on('select(agent)', function(data){
        var user_id = data.value;
        $('.user_id').val(user_id);

        // 选择门店
        $.ajax({
            url : "{{url('/api/user/store_lists')}}",
            data : {
                token:token
                ,user_id:user_id
                ,l:100
            },
            type : 'post',
            success : function(data) {
                var optionStr = "";
                for(var i=0;i<data.data.length;i++){
                    optionStr += "<option value='" + data.data[i].store_id + "'>" + data.data[i].store_name + "</option>";
                }
                $("#schooltype").html('');
                $("#schooltype").append('<option value="">选择门店</option>'+optionStr);
                // layui.form.render('select');
            },
            error : function(data) {
                alert('查找板块报错');
            }
        });
    });

    // 监听输入框的变化，如果为空则清空另一个输入框的值
    $('#start-item-range, #start-item1-range').on('input', function() {
        if ($(this).val() === '') {
            if (this.id === 'start-item-range') {
                $('.start-item').val('')
                $('.end-item').val('')
            } else if (this.id === 'start-item1-range') {
                $('.start-item1').val('')
                $('.end-item1').val('')
            }
        }
    });

    form.on('submit(LAY-app-contlist-search)', function(data){
        let params = {}
        let starttime = $('.start-item').val();
        let endtime = $('.end-item').val();
        let startitem1 = $('.start-item1').val();
        let endtime1 = $('.end-item1').val()
        let startDateBefore = ''
        let endDateBefore = '';
        let startDate = '';
        let endDate = '';
        if(starttime && endtime){
            //处理开始时间和结束时间
            startDate = starttime.length<12 ? starttime + ' 00:00:00' : starttime;
            endDate = endtime.length<12 ? endtime + ' 23:59:59' : endtime;
        }else{
            layer.msg('请选择时间!') 
            return
        }
        if(startitem1 && endtime1){
            //处理对比的开始时间和结束时间
            startDateBefore = startitem1.length<12 ? startitem1 + ' 00:00:00' : startitem1;
            endDateBefore = endtime1.length<12 ? endtime1 + ' 23:59:59' : endtime1;
        }else{
            layer.msg('请选择对比时间!') 
            return
        }
        //执行重载
        var pageLoading = layer.msg('数据请求中..', {
            icon: 16
            ,shade: 0.3
            ,time: false
        });
        params = {
            store_pid:$('.store_id').val(),
            agent_id:$('.user_id').val(),
            startDate:startDate,
            endDate:endDate,
            startDateBefore:startDateBefore,
            endDateBefore:endDateBefore,
            trend_rate_min:$('.trend_rate_min').val(),
            trend_rate_max:$('.trend_rate_max').val(),
            token:token
        }
        console.log(params,'111')
        tableId.reload({
            url: "{{url('/api/v2/Bill/User/TrendChart/agentTrend')}}",
            where: params,
            page: {
                curr: 1 //重新从第 1 页开始
            },
            done:function(res, curr, count){
                layer.close(pageLoading);
            }
        });
    })

    $('.export').click(function(){
        let params = {}
        let starttime = $('.start-item').val();
        let endtime = $('.end-item').val();
        let startitem1 = $('.start-item1').val();
        let endtime1 = $('.end-item1').val()
        let startDateBefore = ''
        let endDateBefore = '';
        let startDate = '';
        let endDate = '';
        if(starttime && endtime){
            //处理开始时间和结束时间
            startDate = starttime.length<12 ? starttime + ' 00:00:00' : starttime;
            endDate = endtime.length<12 ? endtime + ' 23:59:59' : endtime;
        }else{
            layer.msg('请选择时间!') 
            return
        }
        if(startitem1 && endtime1){
            //处理对比的开始时间和结束时间
            startDateBefore = startitem1.length<12 ? startitem1 + ' 00:00:00' : startitem1;
            endDateBefore = endtime1.length<12 ? endtime1 + ' 23:59:59' : endtime1;
        }else{
            layer.msg('请选择对比时间!') 
            return
        }
        var exportLoading = layer.msg('数据导出中..', {
            icon: 16
            ,shade: 0.3
            ,time: false
        });
        params = {
            store_pid:$('.store_id').val(),
            agent_id:$('.user_id').val(),
            startDate:startDate,
            endDate:endDate,
            startDateBefore:startDateBefore,
            endDateBefore:endDateBefore,
            trend_rate_min:$('.trend_rate_min').val(),
            trend_rate_max:$('.trend_rate_max').val(),
            token:token
        }
        $.ajax({
            url : "{{url('/api/v2/Bill/User/TrendChart/agentTrendExport')}}",
            data : params,
            type : 'post',
            success : function(data) {
                layer.close(exportLoading);
                if(data){
                    let returnData = JSON.parse(data);
                    if (returnData.status == 1) {
                        let urls = returnData.data ? returnData.data.replace(/http:\/\//i, 'https://'):'';
                        urls && (window.location.href=urls);
                    } else {
                        alert(returnData.message);
                    }
                }
            },
            error : function(data) {
                layer.close(exportLoading);
                alert('查找板块报错');
            }
        });
    })
});

</script>

</body>
</html>
